package com.dongdongshop.mq;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.SeckillConstant;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@RocketMQMessageListener(topic = SeckillConstant.SECKILL_GOODS_TOPIC,consumerGroup = SeckillConstant.SECKILL_CONSUMER_GROUP)
public class SeckillConsumer implements RocketMQListener<String> {

    @Resource
    private TbSeckillOrderMapper seckillOrderMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String message) {
        JSONObject json = JSONObject.parseObject(message);
        String userName = (String) json.get("userName");
        Integer seckillGoodsId = (Integer) json.get("seckillGoodsId");
        Long goodsId = seckillGoodsId.longValue();
        TbSeckillGoods seckillGoods = (TbSeckillGoods) redisTemplate.boundHashOps(SeckillConstant.SECKILL_LIST).get(goodsId);
        //下单
        TbSeckillOrder order = new TbSeckillOrder();
        long orderId = idWorker.nextId();
        order.setId(orderId);
        order.setUserId(userName);
        order.setStatus("0");//未支付
        order.setCreateTime(new Date());
        order.setMoney(seckillGoods.getCostPrice());//真实支付价格,也就是秒杀价格
        order.setSellerId(seckillGoods.getSellerId());
        order.setSeckillId(goodsId);
        //为什么先下单再填收货地址,因为如果先填写收货地址,那么很多用户在填写地址的时候别人就买完了
        seckillOrderMapper.insertSelective(order);
        //下单成功,将用户的订单存放到redis中
        redisTemplate.boundValueOps(SeckillConstant.SECKILL_ORDER+userName).set(orderId);
    }
}
